﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using XF.Common;
using XF.Common.Redis;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.Query;
using XF.Meeting.Entity.View;
using XF.Meeting.Entity.CommonEntity.wx;
using XF.Meeting.DAL;

namespace XF.Meeting.Common
{
    public class WeChatHelper
    {
        //ISettingDal settingDal = DalFactory.DalFactory.GetSettingDaL();
        private XF.Common.WeChat.HttpClientHelper requst = new XF.Common.WeChat.HttpClientHelper();
        private string ACCESS_TOKEN { get; set; }
        private WxConfig Wx { get; set; }
        public WeChatHelper()
        {
            var dal = new BPMDal();
           
            var result =  dal.GetWXCONFIG(out string s);
            Wx = XF.Common.TableToList.ToList<WxConfig>(result.Result).FirstOrDefault();
            ACCESS_TOKEN = GetAccessToken(Wx.Corpid, Wx.Secret);
        }
        public void SendTextMessage(Message message)
        {
            message.agentid = Convert.ToInt32(Wx.AgentId);
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(message));
        }

        public string GetAccessToken(string corpid, string secret)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}");
            // Response.Write(response);
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return aaa.access_token;
        }
        public string GetUserId(string Code)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={ACCESS_TOKEN}&code={Code}");
            var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return aaa.UserId;
        }
        public string GetUserInfo(string UserId)
        {

            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token={ACCESS_TOKEN}&userid={UserId}");
            //  var aaa = Newtonsoft.Json.JsonConvert.DeserializeObject<Root>(response);
            return response;
        }
        public string CreateChatId(WeChat_Chat enity)
        {


            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new CreateChat
            ()
            {
                name = enity.name,
                owner = enity.owner,
                userlist = enity.userList,
                chatid = enity.chatid
            }));

            return enity.chatid;
        }

        public string SendMessageForGroup(WeChat_Chat_Msg entity)
        {
            var response = requst.Post($"https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token={ACCESS_TOKEN}", JsonConvert.SerializeObject(new ChatInfo()
            {
                chatid = entity.ChatId,
                msgtype = entity.MsgType,
                safe = 0,
                text = new Text(entity.Msg)
            }
          ));
            return response;
        }
        /// <summary>
        /// 获取部门信息，
        /// </summary>
        /// <param name="id">为0查询全部</param>
        /// <returns></returns>
        public Task<Departments> GetDepartments(int id = 0)
        {
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={ACCESS_TOKEN}&id={id}");
            var depList = JsonConvert.DeserializeObject<Departments>(response);
            return Task.FromResult(depList);
        }
        public Task<userList> GetUserList(int minId, int fetch_child)
        {
            var response = requst.Get($"https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={ACCESS_TOKEN}&department_id={minId}&fetch_child={fetch_child}");
            var list = JsonConvert.DeserializeObject<userList>(response);
            return Task.FromResult(list);
        }
        public void SendWxMssage(CRoomPadQuery query, bool isTen = false)
        {
            bool isZhouqi = false;
            var dal = new MeetingDal();
            int ID = 0;
            //if (query.type == 2)
            //{
            //    var cInfo = dal.getMeetIdBystrBOID(query.strBOID);
            //    if (cInfo.CycleMeetType > 0)
            //    {
            //        isZhouqi = true;
            //    }
            //    else
            //    {
            //        ID = cInfo.CInfoID;
            //    }
            //}
            //else
            //{
            //    ID = query.CInfoId;
            //}
            ID = query.CInfoId;
            if (!isZhouqi)
            {
                if (!dal.IsSendWX(ID, out string error))
                {


                    var res = dal.GetCInfoByID(ID).Result;

                    var list = XF.Common.TableToList.ToList<MeetingInfoSingle>(res);
                    var meetingInfoSingle = list[0];
                    if (meetingInfoSingle.EndTime < DateTime.Now)
                    {
                        return;
                    }
                    meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
                    meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
                    meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
                    if (string.IsNullOrEmpty(meetingInfoSingle.CRooms))
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom;
                    }
                    else
                    {
                        meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + meetingInfoSingle.CRooms;
                    }

                    var msgList = dal.getMeetInfoAndUserPhone(ID, out string StrError);
                    var phoneList = XF.Common.TableToList.ToList<meetIdS>(msgList.Tables[0]);
                    var userlist = phoneList.Select(i => i.Account).ToList();
                    var userr = GetUserString(userlist);
                    //由XXX召集的会议《XXXX》，将于X月X日X时X分，在X楼X会议室召开。请您准时出席。

                    if (isTen)
                    {
                        var msg = new Message(new Text($"由{meetingInfoSingle.CoordinatorName}召集的会议《{meetingInfoSingle.ConferenceTheme}》，将于 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}，在{meetingInfoSingle.Remark}{meetingInfoSingle.CRoom}召开。现在距离开会还有10分钟，请您准时出席。"), userr);

                        this.SendTextMessage(msg);
                        dal.updateWxState(ID, out string strError);
                    }
                    else
                    {
                        if (query.type == 3)
                        {
                            var msg = new Message(new Text($"（周期会议） 由{meetingInfoSingle.CoordinatorName}召集的会议《{meetingInfoSingle.ConferenceTheme}》，将于 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}，在{meetingInfoSingle.Remark}{meetingInfoSingle.CRoom}召开,请您准时出席。"), userr);
                            this.SendTextMessage(msg);
                        }
                        else {
                            var msg = new Message(new Text($"由{meetingInfoSingle.CoordinatorName}召集的会议《{meetingInfoSingle.ConferenceTheme}》，将于 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}，在{meetingInfoSingle.Remark}{meetingInfoSingle.CRoom}召开,请您准时出席。"), userr);
                            this.SendTextMessage(msg);
                        }
                       

                      
                    }
                }
            }



        }
        public async void SendChnnelMsg(int id,bool isZhouqi)
        {
            var dal = new MeetingDal();
            var res = await dal.GetCInfoByID(id);

            var list = XF.Common.TableToList.ToList<MeetingInfoSingle>(res);
            var meetingInfoSingle = list[0];
            if (meetingInfoSingle.EndTime < DateTime.Now)
            {
                return;
            }
            meetingInfoSingle.date = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("yyyy-MM-dd");
            meetingInfoSingle.Begin = Convert.ToDateTime(meetingInfoSingle.BeginTime).ToString("HH:mm");
            meetingInfoSingle.End = Convert.ToDateTime(meetingInfoSingle.EndTime).ToString("HH:mm");
            if (string.IsNullOrEmpty(meetingInfoSingle.CRooms))
            {
                meetingInfoSingle.CRooms = meetingInfoSingle.CRoom;
            }
            else
            {
                meetingInfoSingle.CRooms = meetingInfoSingle.CRoom + meetingInfoSingle.CRooms;
            }

            var msgList = dal.getMeetInfoAndUserPhone(id, out string StrError);
            var phoneList = XF.Common.TableToList.ToList<meetIdS>(msgList.Tables[0]);
            var userlist = phoneList.Select(i => i.Account).ToList();
            var userr = GetUserString(userlist);
            Text text = null;
            //XXX邀请您参加《XXXXX》会议，时间：2020-07-29 18:40~19:00，地点：XXXX，主持人：XXXX，请准时出席。
            if (isZhouqi)
            {
                text = new Text($"已取消(周期会议): 由{meetingInfoSingle.CoordinatorName}召集的会议《{meetingInfoSingle.ConferenceTheme}》，于 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}，在{meetingInfoSingle.Remark}{meetingInfoSingle.CRoom}召开，此周期会议已取消请知悉。");
            }
            else {
                text = new Text($"已取消: 由{meetingInfoSingle.CoordinatorName}召集的会议《{meetingInfoSingle.ConferenceTheme}》，于 {meetingInfoSingle.date}  {meetingInfoSingle.Begin}，在{meetingInfoSingle.Remark}{meetingInfoSingle.CRoom}召开，此会议已取消请知悉。");
            }
            var msg = new Message(text, userr);
            //var msg = new Message(new Text($"请您参加于{meetingInfoSingle.date}，{meetingInfoSingle.Begin}到{meetingInfoSingle.End}，在（{meetingInfoSingle.CRooms}）举行的由（{meetingInfoSingle.HostPersonName}）主持的（{meetingInfoSingle.ConferenceTheme})主题会议，望准时参加!"), userr);
            this.SendTextMessage(msg);
        }
        public async void senNotAcceptMsg(string mailAddress,string subject, string bO,DateTime start, DateTime end)
        {
            var service = new UserDAL();
            var res = await service.GetUserAccountByMail(mailAddress,out string error);
            var phoneList = XF.Common.TableToList.ToList<meetIdS>(res.Item1);
            //var userlist = phoneList.Select(i => i.Account).ToList();
            //var userr = GetUserString(userlist);
            var msg = new Message(new Text($"您召集的会议《{subject}》，将于 { Convert.ToDateTime(start).ToString("yyyy-MM-dd")}  {Convert.ToDateTime(start).ToString("HH:mm")}开始的会议与{bO}会议室时间冲突，请重新选择会议时间"), phoneList[0].Account);
            SendTextMessage(msg);
        }


        public static string GetUserString(List<string> userList)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in userList)
            {
                //if (string.IsNullOrWhiteSpace(RedisCache.Hash_Get<string>("UserPhone", item)))
                //{
                //    continue;
                //}

                sb.Append(item);
                sb.Append("|");
            }
            sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }

    }
    public class meetIdS
    {
        public int ID { get; set; }
        public string Phone { get; set; }
        public string Account { get; set; }
    }
}
